package com.hedd.shop.service.impl;

import com.hedd.shop.pojo.entity.User;
import com.hedd.shop.pojo.entity.UserInfo;
import com.hedd.shop.pojo.receptparms.UserUpdateQo;
import com.hedd.shop.pojo.vo.RespResult;
import com.hedd.shop.exceptions.ShopException;
import com.hedd.shop.mapper.UserInfoMapper;
import com.hedd.shop.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfo userInfo(Long id) {
        UserInfo userInfo = userInfoMapper.userInfo(id);

       if(userInfo==null){
           throw new ShopException(RespResult.Code.FAILED.getValue(),"尚未填写信息");
       }
        return userInfo;
    }

    @Override
    public int updateUserInfoById(UserUpdateQo userUpdateQo, MultipartFile file) throws IOException {
        UserInfo userInfo = userInfoMapper.userInfo(userUpdateQo.getId());
        if(userInfo==null){
            int i = userInfoMapper.insertUserInfo(userUpdateQo.getId());
            if (i!=1){
                throw new ShopException("修改失败");
            }
        }
        if(!file.isEmpty()){
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //判断类型是否为图片，否则禁止上存
            String contentType = file.getContentType();
                if(!contentType.equals("image/jpeg")){
                throw new ShopException(RespResult.Code.FAILED.getValue(),"上存文件格式错误");
            }
            //获得文件后缀名称
            String typeName=contentType.substring(contentType.indexOf("/")+1);
            String imageName=uuid+"."+typeName;
            String path="D:/2003LDH/shop/views/shop-center/assets/userportrait/"+imageName;
            file.transferTo(new File(path));
            //路径放到用户信息中
            userUpdateQo.setPortrait("assets/userportrait/"+imageName);
        }
        System.out.println( userUpdateQo.toString());
        userUpdateQo.setId(1L);
        int update = userInfoMapper.updateUserInfoById(userUpdateQo);
        if(update!=1){
            throw new ShopException("修改失败");
        }
        return RespResult.Code.SUCCESS.getValue();
    }


}
